package org.ly.sys.module;

import org.ly.sys.bean.User;
import org.ly.utils.MD5;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.Date;

/**
 * 
 * @author liuyong
 *
 *   主页Module 
 */
@At("/sys")
@IocBean
public class indexModule {

	@Inject
	UserModule userModule;
	
	@At("/login")
	@Ok("jsp:views.sys.login")
	public void goLogin(){
	}
	
	@At("/left")
	@Ok("jsp:views.sys.left")
	public void goLeft(){
	}
	
	@At("/top")
	@Ok("jsp:views.sys.top")
	public void goTop(){
	}
	
	@At("/mainfra")
	@Ok("jsp:views.sys.mainfra")
	public void goMainfra(){
	}
	
	/**
	 * 登录
	 * @param user
	 * @param session
	 * @param request
	 */
	@At("/index")
	@Ok("jsp:views.sys.index")
	@Fail("jsp:views.sys.login")
	@Filters
	public void login(@Param("..") User user, HttpSession session, HttpServletRequest request) {
		//从数据库获取user
		User dataUser = userModule.fetch(Cnd.where("name", "=", user.getName()).and("password", "=", MD5.getMd5(user.getPassword())));
		//如返回为null返回登录页面
		if(null == dataUser){
			request.setAttribute("error", Mvcs.getMessage(request, "loginerror"));
			throw new RuntimeException("Error username or password");
		}
		Date date = new Date();
		dataUser.setZuihoudengl(date);
		System.out.println(date.toString());
		userModule.update(dataUser);
		session.setAttribute("loginuser", dataUser);
		session.setAttribute("username", dataUser.getName());
	}
	
	/**
	 * 
	 * @param session
	 * 注销
	 */
	@At("/logout")
	@Ok("jsp:views.sys.login")
	public void logout(HttpSession session){
		session.removeAttribute("loginuser");
		session.removeAttribute("username");
	}
}
